#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/3/27 0:06
# @Author  : Grayson Liu
# @Email   : graysonliu@foxmail.com
# @File    : CustomFigureCanvas.py

import matplotlib
from PyQt5.QtWidgets import QSizePolicy

matplotlib.use("Qt5Agg")

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

import numpy as np


class CustomFigureCanvas(FigureCanvas):
    """
    自定义的适用于Qt Widget的matplotlib组件，可用于显示图像和绘制图表
    """

    def __init__(self, parent=None, width=30, height=30, dpi=100):
        """
        初始化
        :param parent:
        :param width:
        :param height:
        :param dpi:
        """
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        self.fig.subplots_adjust(left=0.10, right=0.90, top=0.98, bottom=0.02)  # 调整边缘的空白，使得Canvas的利用更充分

        self.axes = self.fig.add_subplot(1, 1, 1)  # 111”表示“1×1网格，第1个子图
        self.axes.grid(b=False)  # 不显示网格
        self.axes.set_axis_off()
        self.axes.set_xticks([])  # 不显示坐标轴
        self.axes.set_yticks([])

        super(CustomFigureCanvas, self).__init__(self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)

    def show_picture(self, pic_array):
        """
        在空间上画出灰度图像
        :param pic_array: 灰度图像矩阵，是np.ndarray
        :return: None
        """
        self.axes.cla()
        self.axes.set_axis_off()
        self.axes.imshow(pic_array, cmap="gray_r")
        self.draw()

    def show_hist(self, pic_array):
        """
        画出灰度直方图
        :return:
        """
        hist, bins = np.histogram(pic_array, bins=256, range=[0, 256])
        self.axes.cla()
        self.axes.plot(hist, color="g")
        self.axes.axis([0, 256, 0, np.max(hist)])
        self.draw()

    def show_ndvi_chart(self, max_ndvi: list, min_ndvi: list):
        """
        画出NDVI指数的折线图，有2条折线：NDVI的最大值和最小值
        :param max_ndvi:
        :param min_ndvi:
        :return:
        """
        self.axes.cla()
        period = [i + 1 for i in range(0, len(max_ndvi))]
        self.axes.grid(b=True)  # 显示网格
        self.axes.set_title("NDVI Period")
        self.axes.set_xlabel("Period")
        self.axes.set_ylabel("NDVI")
        self.axes.plot(period, max_ndvi, "r.-", label="max NDVI")
        self.axes.plot(period, min_ndvi, "b.-", label="min NDVI")
        for a, b in zip(period, max_ndvi):
            self.axes.text(a, b, round(b, 4), ha='center', va='bottom', fontsize=6)
        for a, b in zip(period, min_ndvi):
            self.axes.text(a, b, round(b, 4), ha='center', va='bottom', fontsize=6)
        self.axes.hlines(max(max_ndvi), period[0], period[-1], colors="c", linestyles="dashed")
        self.axes.text(period[-1], max(max_ndvi) + 0.1, "max NDVI={:.4f}".format(max(max_ndvi)),
                       ha='center', va='bottom', fontsize=6)
        self.axes.hlines(min(min_ndvi), period[0], period[-1], colors="c", linestyles="dashed")
        self.axes.text(period[-1], min(min_ndvi) - 0.1, "min NDVI={:.4f}".format(min(min_ndvi)),
                       ha='center', va='top', fontsize=6)
        self.axes.set_yticks(np.arange(-1.0, 1.01, 0.2))
        self.draw()
